<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\admin\model\UserOrder;
use app\admin\model\ProductTake;
use app\admin\model\MpType;
use app\admin\model\ProductMessage;
use app\admin\model\OrderLog;
use app\admin\model\UserOrderAgainst;
use app\admin\model\User;
use app\admin\model\ChatMessage;
use app\api\controller\Pay;
use think\Db;
use getui\GeTui;
use think\Exception;
/**
 * 订单管理列表
 *
 * @icon fa fa-user
 */
class Order extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {   
       
        parent::_initialize();
        $this->model = new UserOrder();
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = json_decode($this->request->get("filter", ''),true);
            if(!empty($filter['status'])){
                $where1 = [];
            }else{
                $where1 = ['status'=>['neq','-1']];
            }
            $list = $this->model
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $MpType = MpType::where(['id'=>$v['mp_type_id']])->find();
                $v['title'] = $MpType['name'];
                $v['username'] = User::where(['id'=>$v['user_id']])->value('nickname');
                $v['mobile'] = User::where(['id'=>$v['user_id']])->value('mobile');
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
     /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if((!empty($params['expressage']) && empty($params['odd']))  || (empty($params['expressage']) && !empty($params['odd']))){
                    $this->error('物流单号和快递名称需要同时填写!');
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    //查询当前订单状态和是否填写了物流信息
                    if(($row['status'] == 2 || $row['status'] == 6) && $params['expressage'] && $params['odd']){
                        //都填写了则更新订单状态为已发货
                        $params['status'] = 3;
                        $params['delivery_time'] = time();
                        if($row['notice'] == 1){
                            //发送订阅消息
                            $product = Product::where('id',$row['product_id'])->find();
                            $data = [
                                "thing10"=>["value"=>$product['title']],
                                "phrase8"=>["value"=>'买家付邮'],
                                "character_string3"=>[ "value"=> $params['odd']], 
                                "thing1"=>["value"=>'你的订单已发货，请及时关注物流信息！' ]
                            ];
                            send_subscription($row['user_id'],'UVo1qW8QNqqYqJwaGDtZ10ianotfn5aHyDC3tSqI2iE','/pages/user/myOrder',$data);
                        }
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $product =  Product::where(['id'=>$row['product_id']])->find();
        //商品名称
        $row['product_name'] = $product['title'];
        //商家id
        $row['shop_id'] = $product['id'];
        //寄件人信息
        $row['jijian'] = $product['name'].$product['phone'].$product['position'].$product['city'].$product['area'].$product['address'];
        //收件人信息
        $row['shoujian'] = $row['address_username'].$row['address_tel'].$row['address_province'].$row['address_city'].$row['address_detail'];
        $row['add_time'] = date('Y-m-d H:i:s',$row['add_time']);

        if($row['status'] == 3 || $row['status'] == 5){
            $row['status_1'] = 1;
        }else{
            $row['status_1'] = 0;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    
   
    /**
     * 订单申述
     */
    public function index_state()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $this->model = new UserOrderAgainst();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $list = UserOrderAgainst::where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $user =  User::where(['id'=>$v['user_id']])->find();
                $list[$k]['nickname'] = $user['nickname'];
            }
        
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

     /**
     * 订单取消
     */
    public function index_qx()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $this->model = new OrderLog();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where1 = [
                'type'=>1
            ];
            $list = OrderLog::where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $user =  User::where(['id'=>$v['user_id']])->find();
                $list[$k]['nickname'] = $user['nickname'];
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function setQxStatus(){
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            Db::startTrans();
            try {
                $result = OrderLog::where(['id'=>$data['id']])->update(['status'=>$data['status']]);
                if ($result) {
                    $log = OrderLog::where(['id'=>$data['id']])->find();
                    $order = UserOrder::where(['id'=>$log['order_id']])->find();
                    if($data['status'] == 1){
                        //同意取消进行退款操作
                        $arr = ['user_id'=>$log['user_id'],'order_id'=>$order['id'],'ship_type'=>$order['ship_type'],'status'=>$order['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                        $product=Product::where(array('id'=>$order['product_id']))->find();
                        if($order['ship_type'] == 1){
                            $arr['text'] = '买家付邮退款';
                            if($order['pay_type'] == 'dy'){
                                $pay = new Pay();
                                $pay->dy_refund($order,$order['pay_fee'],$log['user_id'],$arr);
                            }else{
                                Pay::doOrderRefund($order,$order['pay_fee'],$log['user_id'],$arr);
                            }
                            order_cancel($order);
                        }else{
                            $arr['text'] = '自提取消订单';
                            //退回积分
                            roseandlog($order['user_id'],$order['total_money'],18,'取消订单，退回');
                          
                            ProductMessage::insert(array('product_id'=>$order['product_id'],'title'=>'买家'.$log['user_id'].'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                            Product::where(array('id'=>$order['product_id']))->update(array('is_sale'=>0));
                            UserOrder::where(['id'=>$order['id']])->update(['status'=>-1,'paidui'=>0,'paidui_content'=>'']);
                        }
                        OrderLog::insert($arr);
                        $arr = [
                            'content' => '你的取消申请已成功。',
                            'user_id' => 439,
                            'js_user_id'=> $log['user_id'],
                            'product_id'=>$order['product_id'],
                            'add_time'=>time(),
                        ];
                        $arr['sort'] = $arr['js_user_id'].'0'.$order['product_id'].$arr['user_id'];
                        ChatMessage::insert($arr);

                        if($product['type_status'] < 3){ //积分购买
                            $thing1 = '你的领取订单已被赠送者取消！';
                        }else{
                            $thing1 = '你的购买订单已被卖家取消！';
                        }
                        //发送订阅推送
                        $data = [
                            'thing1'=>['value'=>$thing1],
                            'character_string2'=>['value'=>$order['order_id']],
                            'time3'=>['value'=>date('Y-m-d H:i:s',$order['add_time'])]
                        ];
                        send_subscription($order['user_id'],'2zbsInw2kF2wH4mLA_Z7do7TrpZ3LQBBERm3LzIpCV8','/pages/user/myOrder',$data);

                        //卖家取消给买家发送消息
                        $geTui = new GeTui();
                        //添加成功执行推送逻辑
                        $cid = User::where(['id'=>['in',$order['user_id']]])->value('cid');
                        if($cid){
                            $geTui->pushToSingleByCid($cid,'订单提醒','您兑换的商品已被卖家取消','/pages/user/myOrder');
                        }
                    }else{ // 拒绝  给用户发送一条消息
                        $arr = [
                            'content' => '你的取消申请被拒绝，请联系余享客服处理。',
                            'user_id' => 439,
                            'js_user_id'=> $log['user_id'],
                            'product_id'=>$order['product_id'],
                            'add_time'=>time(),
                        ];
                        $arr['sort'] = $arr['js_user_id'].'0'.$order['product_id'].$arr['user_id'];
                        ChatMessage::insert($arr);

                        //卖家取消被拒绝给卖家发送消息
                        $geTui = new GeTui();
                        //添加成功执行推送逻辑
                        $cid = User::where(['id'=>['in',$order['shop_id']]])->value('cid');
                        if($cid){
                            $geTui->pushToSingleByCid($cid,'订单提醒','您的取消订单申请已被拒绝','/pages/user/sellOrder');
                        }

                    }
                    Db::commit();
                    $this->success();
                } else {
                    Db::commit();
                    $this->error('操作失败');
                }
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }


            
        }
    }
    public function cancelOrder(){
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            $order = UserOrder::where(['id'=>$data['id']])->find();
            if ($order) {
                //取消进行退款操作
                
                $arr = ['user_id'=>$order['user_id'],'order_id'=>$order['id'],'ship_type'=>$order['ship_type'],'status'=>$order['status'],'add_time'=>date('Y-m-d H:i:s',time())];
                if($order['ship_type'] == 1){
                    $arr['text'] = '买家付邮退款';
                    if($order['pay_type'] == 'dy'){
                        $pay = new Pay();
                        $pay->dy_refund($order,$order['pay_fee'],$order['user_id'],$arr);
                    }else{
                        Pay::doOrderRefund($order,$order['pay_fee'],$order['user_id'],$arr);
                    }
                    order_cancel($order);
                }else{
                    $arr['text'] = '自提取消订单';
                    //退回积分
                    roseandlog($order['user_id'],$order['total_money'],18,'取消订单，退回');
                    $product=Product::where(array('id'=>$order['product_id']))->find();
                    ProductMessage::insert(array('product_id'=>$order['product_id'],'title'=>'买家'.$order['user_id'].'取消订单，取消发货:【'.$product['title'].'】','user_id'=>$order['user_id'],'to_user_id'=>$product['user_id'],'is_read'=>0,'type'=>3,'status'=>1,'add_time'=>time()));
                    Product::where(array('id'=>$order['product_id']))->update(array('is_sale'=>0));
                    UserOrder::where(['id'=>$order['id']])->update(['status'=>-1,'paidui'=>0,'paidui_content'=>'']);
                }
                OrderLog::insert($arr);
                $this->success();
            } else {
                $this->error('操作失败');
            }
        }
    }

    


    /**
     * 查看
     */
    public function product_take()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('id',null,new ProductTake());
            $filter = json_decode($this->request->get("filter", ''),true);
           
            $list = ProductTake::where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $v['nickname'] = User::where(['id'=>$v['user_id']])->value('nickname');
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function product_take_cancelOrder(){
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            $order = ProductTake::where(['id'=>$data['id']])->find();
            if ($order) {
                ProductTake::where(['id'=>$order['id']])->update(['status'=>-1]);
                $this->success();
            } else {
                $this->error('操作失败');
            }
        }
    }
    //取消快递
    public function product_take_kuaidi(){
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            $order = ProductTake::where(['id'=>$data['id'],'status'=>1])->find();
            if ($order) {
                ProductTake::where(['id'=>$order['id']])->update(['status'=>-1]);
                order_cancel($order);
                $this->success();
            } else {
                $this->error('操作失败');
            }
        }
    }
    //同意
    public function product_take_set_status(){
        if ($this->request->isPost()) {
            $data = $this->request->request();
            if(!$data['id']){
                $this->error('参数错误');
            }
            $order = ProductTake::where(['id'=>$data['id']])->find();
            if ($order) {

                //发货
                $data = $this->send_expressage($order);
                if($data){
                    $where['status'] = 1;
                    $where['taskId'] = $data['taskId'];
                    $where['orderId'] = $data['orderId'];
                    $where['kuaidinum'] = $data['kuaidinum'];
                    ProductTake::where(['id'=>$order['id']])->update($where);
                }else{
                    $this->error('下单失败,请联系管理员');
                }

                $this->success();
            } else {
                $this->error('操作失败');
            }
        }
    }


    

    //发送快递
	public function send_expressage($order = [],$day = '',$time = ''){
		//判断物品重量
		if($order['weight'] < 3){
			$kuaidicom = 'jd';
			$expressage = '京东';
           /*  $kuaidicom = 'debangkuaidi';
			$expressage = '德邦'; */
            $serviceType = '标准快递';
		}else{
			$kuaidicom = 'debangkuaidi';
			$expressage = '德邦';
            $serviceType = '德邦大件360';
		}
      
		ProductTake::where(['id'=>$order['id']])->update(['expressage'=>$expressage]);
		
		$param = [
			'kuaidicom' => $kuaidicom,        
			'recManName' => '张燚',              
			'recManMobile' => '13554694311',                        
			'recManPrintAddr' => '湖北省武汉市汉阳区龙阳时代-B座808',           
			'sendManName' => $order['address_username'],         
			'sendManMobile' =>  $order['address_tel'],                 
			'sendManPrintAddr' => $order['address_province'].$order['address_city'].$order['address_district'].$order['address_detail'],           
			'callBackUrl' => $this->request->root(true) . '/api/order/notifyx',          
			'cargo'=>'余享商品',
			'weight'=>(string)$order['weight'],
			"payment"=>"",
			"serviceType"=>$serviceType,
			"remark"=>"",
			"salt"=>"",
			"dayType"=>"",
			"pickupStartTime"=>"",
			"pickupEndTime"=>"",
			"valinsPay"=>"",
			"passwordSigning"=>"N",
			"op"=>"0",
			"pollCallBackUrl"=>"",
			"resultv2"=>"0",
			"returnType"=>"0",
			"siid"=>"",
			"tempid"=>"",
			"printCallBackUrl"=>""
		];
       
		$param = json_encode($param, JSON_UNESCAPED_UNICODE);
		$t = time() * 1000;
		$post_data = [

			'key'=>'wlSuxIGP3476',
			'sign'=>strtoupper(MD5($param.$t.'wlSuxIGP3476'.'155d139726d040e88207b0cc03481efa')),
			't'=>$t,
			'param'=>$param
		];

		db('log')->insert(['order_id'=>$order['id'],'text'=>$param,'type'=>'发送快递下单参数','add_time'=>date('Y-m-d H:i:s',time())]);
		
		//$url = 'https://api.kuaidi100.com/apiMock/border?method=bOrder';
		$url = 'https://poll.kuaidi100.com/order/borderapi.do?method=bOrder';
		// 发送post请求
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		$result = curl_exec($ch);
		$data = json_decode($result, true);

		OrderLog::insert(['order_id'=>$order['id'],'text'=>'预约快递','user_id'=>$order['user_id'],'add_time'=>date('Y-m-d H:i:s' ,time()) ,'ship_type'=>1,'status'=>2,'json'=>$result]);
		if($data['result'] && $data['returnCode'] == 200){
			return $data['data'];
		}else{
			return false;
		}
	}

}
